/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.manage.theme.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.core.consts.CommonConstant;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.manage.biindexdata.entity.BiIndexData;
import vip.xiaonuo.modular.manage.biindexdata.service.BiIndexDataService;
import vip.xiaonuo.modular.manage.poidata.entity.BiPoiData;
import vip.xiaonuo.modular.manage.poidata.service.PoiDataService;
import vip.xiaonuo.modular.manage.poidatatags.service.PoiDataTagsService;
import vip.xiaonuo.modular.manage.theme.entity.BiTheme;
import vip.xiaonuo.modular.manage.theme.entity.BiThemeIndex;
import vip.xiaonuo.modular.manage.theme.enums.ThemeExceptionEnum;
import vip.xiaonuo.modular.manage.theme.mapper.ThemeMapper;
import vip.xiaonuo.modular.manage.theme.param.ThemeParam;
import vip.xiaonuo.modular.manage.theme.service.ThemeIndexService;
import vip.xiaonuo.modular.manage.theme.service.ThemeService;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 主题管理service接口实现类
 *
 * @author cy
 * @date 2022-07-28 19:43:15
 */
@Service
public class ThemeServiceImpl extends ServiceImpl<ThemeMapper, BiTheme> implements ThemeService {
    @Resource
    private ThemeIndexService themeIndexService;

    @Resource
    private BiIndexDataService biIndexDataService;

    @Resource
    private PoiDataService poiDataService;

    @Resource
    private PoiDataTagsService poiDataTagsService;

    @Override
    public PageResult<BiTheme> page(ThemeParam themeParam) {
        QueryWrapper<BiTheme> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(themeParam)) {

            // 根据主题名称 查询
            if (ObjectUtil.isNotEmpty(themeParam.getName())) {
                queryWrapper.lambda().eq(BiTheme::getName, themeParam.getName());
            }
            // 根据主题描述 查询
            if (ObjectUtil.isNotEmpty(themeParam.getDescribeMsg())) {
                queryWrapper.lambda().eq(BiTheme::getDescribeMsg, themeParam.getDescribeMsg());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<BiTheme> list(ThemeParam themeParam) {
        QueryWrapper<BiTheme> queryWrapper = new QueryWrapper<>();
        if (themeParam != null) {
            if (ObjectUtil.isNotEmpty(themeParam.getName())) {
                queryWrapper.lambda().like(BiTheme::getName, themeParam.getName());
            }
        }
        List<BiTheme> list = this.list(queryWrapper);
        list.forEach(e ->{
            if("N".equalsIgnoreCase(e.getStatus()) ){
                e.setDisabled(true);//启用/停用 Y/N',
            }else{
                e.setDisabled(false);
            }
        });
        return list;
    }



    @Override
    public void add(ThemeParam themeParam){
        System.out.println(themeParam);
        BiTheme theme = new BiTheme();
        BeanUtil.copyProperties(themeParam, theme);
        theme.setStatus(CommonConstant.STATUS_Y);
        this.save(theme);
        if (ArrayUtil.isNotEmpty(themeParam.getCheckedKeys())) {
            List<String> indexKeys = Arrays.asList(themeParam.getCheckedKeys());
            List<BiThemeIndex> indexList = indexKeys.stream().map(o->{
                BiThemeIndex index = new BiThemeIndex();
                index.setThemeId(theme.getId());
                index.setIndexId(Long.parseLong(o));
                index.setPoiOrIndex("indexType");
                return index;
            }).collect(Collectors.toList());
            themeIndexService.saveBatch(indexList);
        }

        if (ArrayUtil.isNotEmpty(themeParam.getCheckedPoiKeys())) {
            List<String> poiKeys = Arrays.asList(themeParam.getCheckedPoiKeys());
            List<BiThemeIndex> poiList = poiKeys.stream().map(o->{
                BiThemeIndex poi = new BiThemeIndex();
                poi.setThemeId(theme.getId());
                poi.setPoiId(Long.parseLong(o));
                poi.setPoiOrIndex("poiType");
                return poi;
            }).collect(Collectors.toList());
            themeIndexService.saveBatch(poiList);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<ThemeParam> themeParamList) {
        themeParamList.forEach(themeParam -> {
            this.removeById(themeParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void status(ThemeParam themeParam) {
        BiTheme biTheme = getBaseMapper().selectById(themeParam.getId());
        biTheme.setStatus(CommonConstant.STATUS_Y.equals(biTheme.getStatus())?CommonConstant.STATUS_N:CommonConstant.STATUS_Y);
        biTheme.setUpdateTime(new Date());
        this.updateById(biTheme);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ThemeParam themeParam) {
        BiTheme theme = this.queryTheme(themeParam);
        BeanUtil.copyProperties(themeParam, theme);
        this.updateById(theme);

        //先删除所有的BiThemeIndex
        themeIndexService.remove(new QueryWrapper<BiThemeIndex>().lambda().eq(BiThemeIndex::getThemeId, themeParam.getId()));
        //后重新写入
        if (ArrayUtil.isNotEmpty(themeParam.getCheckedKeys())) {
            List<String> indexKeys = Arrays.asList(themeParam.getCheckedKeys());
            List<BiThemeIndex> indexList = indexKeys.stream().map(o->{
                BiThemeIndex index = new BiThemeIndex();
                index.setThemeId(theme.getId());
                index.setIndexId(Long.parseLong(o));
                index.setPoiOrIndex("indexType");
                return index;
            }).collect(Collectors.toList());
            themeIndexService.saveBatch(indexList);
        }
        if (ArrayUtil.isNotEmpty(themeParam.getCheckedPoiKeys())) {
            List<String> poiKeys = Arrays.asList(themeParam.getCheckedPoiKeys());
            List<BiThemeIndex> poiList = poiKeys.stream().map(o->{
                BiThemeIndex poi = new BiThemeIndex();
                poi.setThemeId(theme.getId());
                poi.setPoiId(Long.parseLong(o));
                poi.setPoiOrIndex("poiType");
                return poi;
            }).collect(Collectors.toList());
            themeIndexService.saveBatch(poiList);
        }

//                                      ThemeIndexParam themeIndexParam = new ThemeIndexParam();
//        themeIndexParam.setThemeId(themeParam.getId());
//        List<BiThemeIndex> themeIn dexList = themeIndexService.list(themeIndexParam);
//        themeIndexList.forEach(biThemeIndex -> {
//            themeIndexService.removeById(biThemeIndex.getId());
//        });

    }

    @Override
    public BiTheme detail(ThemeParam themeParam) {
        return this.queryTheme(themeParam);
    }

    /**
     * 获取主题管理
     *
     * @author cy
     * @date 2022-07-28 19:43:15
     */
    private BiTheme queryTheme(ThemeParam themeParam) {
        BiTheme theme = this.getById(themeParam.getId());
        if (ObjectUtil.isNull(theme)) {
            throw new ServiceException(ThemeExceptionEnum.NOT_EXIST);
        }
        return theme;
    }

    @Override
    public void export(ThemeParam themeParam) {
        List<BiTheme> list = this.list(themeParam);
        PoiUtil.exportExcelWithStream("SnowyTheme.xls", BiTheme.class, list);
    }

    @Override
    public Long[] themeTree(List<BiThemeIndex> themeIndexs) {
        Long[] nodes = new Long[themeIndexs.size()];
        for(int i=0;i<themeIndexs.size();i++){
            nodes[i] = themeIndexs.get(i).getIndexId();
        }
        return nodes;
    }

    @Override
    public BiTheme findThemeAndData(ThemeParam themeParam) {
//      主题
        BiTheme biTheme = new BiTheme();
        if (ObjectUtil.isNotNull(themeParam)){
            biTheme = this.getById(themeParam.getId());
//      主题对应的指标类型ids
            List<Long> indexIds = this.themeIndexService.findindexIds(themeParam.getId());
//      根据指标类型ids查询指标数据
            if (indexIds.size() !=0){
                List<BiIndexData> byTypeIds = biIndexDataService.findByTypeIds(indexIds);
                biTheme.setBiIndexDataList(byTypeIds);
            }

//      查询poi数据
            List<Long> poiIds = this.themeIndexService.findPoiIds(themeParam.getId());
            if (poiIds.size() != 0 ){
                List<String> poiNameByIds = poiDataTagsService.findPoiNameByIds(poiIds);
                List<BiPoiData> byTagName = poiDataService.findByTagName(poiNameByIds);
                biTheme.setBiPoiDataList(byTagName);
            }
        }

        return biTheme;
    }
}
